package com.rykj.api

import android.util.Log
import com.rykj.BuildConfig
import com.rykj.util.CacheHelper
import okhttp3.Interceptor.Companion.invoke
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.util.concurrent.TimeUnit

/**
 * description:
 * <p/>
 * Created by ycw on 2020/04/18.
 */
object OkHttpHelper {

    val CONNECT_TIME_OUT: Long = 20
    val READ_TIME_OUT: Long = 20

    var okHttpClient: OkHttpClient? = null

    private val interceptor = invoke { chain ->
        val build = chain.request().newBuilder()
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Authorization", CacheHelper.getInstance().token)
                .build()
        val response = chain.proceed(build)
        Log.i("info", response.request.url.toString())
        response
    }

    fun createOkHttp(): OkHttpClient {
        //增加头部信息
        if (okHttpClient == null) {
            val builder = OkHttpClient().newBuilder()
            builder.connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS)
                    // .addInterceptor(new AddCookiesInterceptor())
                    .addInterceptor(interceptor).readTimeout(READ_TIME_OUT, TimeUnit.SECONDS).writeTimeout(READ_TIME_OUT, TimeUnit.SECONDS)
            if (BuildConfig.DEBUG) {
                //builder.addInterceptor(LoggingInterceptor())
                builder.addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY })
            }
            okHttpClient = builder.build()
        }

        return okHttpClient!!
    }


}